package com.jjlin.chapter_3;

import java.util.*;
public class CD179{
    //二叉树节点
    public static class Node{
        public int val;
        public Node left;
        public Node right;
        public Node(int data){
            this.val = data;
        }
    }

    //建立二叉树
    public static HashMap<Integer, Node> creatNodeList(int[][] nums){
        HashMap<Integer, Node> map = new HashMap<>();
        for(int i = 0; i < nums.length; i++){
            map.putIfAbsent(nums[i][0], new Node(nums[i][0]));
            if(nums[i][1] != 0){
                map.putIfAbsent(nums[i][1], new Node(nums[i][1]));
                map.get(nums[i][0]).left = map.get(nums[i][1]);
            }
            if(nums[i][2] != 0){
                map.putIfAbsent(nums[i][2], new Node(nums[i][2]));
                map.get(nums[i][0]).right = map.get(nums[i][2]);
            }
        }
        return map;
    }

    //以head为根节点的二叉树的节点间最大距离
    public static int maxDistance(Node head){
        if(head == null)
            return 0;
        int[] record = new int[1];//记录节点的子树的节点到子树的最远距离
        return posOrder(head, record);
    }

    //后序遍历
    public static int posOrder(Node head, int[] record){
        if(head == null){
            record[0] = 0;
            return 0;
        }
        int maxl = posOrder(head.left, record);//记录左子树最大
        int maxFromLeft = record[0];//记录左子树上离head.left最远距离
        int maxr = posOrder(head.right, record);//记录右子树最大
        int maxFromRight = record[0];//记录右子树上离head.right最远距离
        int curNodeMax = maxFromLeft + maxFromRight + 1;//跨head的节点间最远距离
        record[0] = Math.max(maxFromRight, maxFromLeft) + 1;//head的子树节点离head节点的最远距离
        return Math.max(Math.max(maxl, maxr), curNodeMax);
    }

    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int root = sc.nextInt();
        int[][] nums = new int[n][3];
        for(int i = 0; i < n; i++)
            for(int j = 0; j < 3; j++)
                nums[i][j] = sc.nextInt();
        HashMap<Integer, Node> map = creatNodeList(nums);
        Node head = map.get(root);
        System.out.println(maxDistance(head));
    }
}

